<template>
	<view class="add-installation-container">
		<status-bar bgColor="#0088ff"></status-bar>

		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="back-btn" @click="goBack">
				<image src="/static/images/icon/backward_flat.png" class="back-icon-img"></image>
			</view>
			<view class="nav-title">安装数据</view>
		</view>

		<scroll-view scroll-y class="scroll-body">
			<!-- 安装照片 -->
			<view class="block">
				<view class="block-title">安装照片 ({{ form.photos ? form.photos.length : 0 }}/3)</view>
				<view class="photo-list">
					<!-- 已上传的照片 -->
					<view class="photo-item" v-for="(photo, index) in form.photos" :key="index">
						<image :src="photo" class="photo-preview" mode="aspectFill"></image>
						<view class="photo-delete" @click="deletePhoto(index)">
							<text class="delete-icon">×</text>
						</view>
					</view>

					<!-- 上传按钮 -->
					<view class="photo-uploader" :class="{disabled: form.photos.length >= 3}" @click="pickImage"
						v-if="form.photos.length < 3">
						<view class="photo-placeholder">
							<image src="/static/images/icon/camera.png" class="camera-icon"></image>
							<text class="upload-text">点击上传</text>
						</view>
					</view>
				</view>

				<view class="photo-tip" v-if="form.photos.length >= 3">
					<text>最多上传3张照片</text>
				</view>
			</view>

			<view class="divider"></view>

			<!-- 基本信息 -->
			<view class="list">
				<view class="row" :class="{disabled: !canEdit}" @click="openRoomSelector">
					<text class="label">房间名称</text>
					<view class="value">
						<text>{{ form.roomNo || '' }}</text>
					</view>
				</view>

				<view class="row" :class="{disabled: !canEdit}" @click="chooseProduct">
					<text class="label">产品</text>
					<view class="value">
						<text>{{ form.productTypeName || '' }}</text>
					</view>
				</view>

				<view class="row" :class="{disabled: !canEdit}" @click="inputNumber('width', '宽度(米)')">
					<text class="label">宽度</text>
					<view class="value">
						<text>{{ form.windowWidth ? (form.windowWidth + ' 米') : '' }}</text>
					</view>
				</view>

				<view class="row" :class="{disabled: !canEdit}" @click="inputNumber('height', '高度(米)')">
					<text class="label">高度</text>
					<view class="value">
						<text>{{ form.windowHeight ? (form.windowHeight + ' 米') : '' }}</text>
					</view>
				</view>

				<view class="row" :class="{disabled: !canEdit}" @click="chooseQuantity">
					<text class="label">数量</text>
					<view class="value">
						<text>{{ form.installNum }} 件</text>
					</view>
				</view>

				<view class="row" :class="{disabled: !canEdit}" @click="chooseValance">
					<text class="label">有无窗幔</text>
					<view class="value">
						<text>
							{{ form.isCurtains=='2' ? ('有；  窗幔类型：' + (form.curtainsTypeName || '')) : '无' }}
						</text>
					</view>
				</view>
			</view>

			<view class="divider"></view>

			<!-- 附加费用 -->
			<view class="block">
				<view class="block-title">附加费用</view>
				<view class="fees">
					<view class="fee-item" :class="{disabled: !canEdit}" v-for="(fee, idx) in additionalFeeList" :key="idx"
						@click="toggleFee(idx)">
						<text class="fee-name" :class="{ dim: !fee.selected }">{{ fee.projectNameTemp }}</text>
						<text class="fee-price">¥ {{ fee.discountMasterFeeTemp }}</text>
					</view>
				</view>
			</view>



			<view style="height: 120rpx;"></view>
		</scroll-view>

		<!-- 底部费用栏 -->
		<view class="bottom-bar">
			<text class="total-label">费用：</text>
			<text class="total-price">¥ {{ this.masterOrderDataFee }}</text>
			<!-- 预留提交按钮，如需启用可放开
      <button class="submit-btn" @click="submit">提交</button>
      -->
		</view>

		<!-- 房间名称选择弹层 -->
		<!-- <room-name-selector :visible="roomSelectorVisible" :selected="form.roomName" @confirm="onRoomConfirm"
			@cancel="roomSelectorVisible = false" /> -->
	</view>
</template>

<script>
	import {
		confgiList
	} from '@/api/app/master/common'
	import {
		getOrderDataDetail,
		editOrderData
	} from '@/api/app/master/order'
	import {
		uploadImgs
	} from '@/utils/picService'
	// import RoomNameSelector from '@/components/room-name-selector.vue'
	import {
		uploadFile
	} from '@/api/app/master/file'

	export default {
		components: {
			
		},
		data() {
			return {
				id: '',
				productType: [],
				curtainsType: [],
				additionalFee: [],
				remoteFees: [],
				specialWall: [],

				orderId: null,
				roomSelectorVisible: false,
				form: {
					photos: []
				},
				masterOrderDataFee:'',
				// 默认示例，若配置接口可用将覆盖
				productOptions: ['直轨双层', '罗马杆', '弯轨', '电机轨道'],
				valanceOptions: ['包边', '压条', '罗马帘盒'],
				canEdit: true,
				extraFees: [

				],
				additionalFeeList:[],
				
			}
		},
		computed: {
			totalPrice() {
				// 设计图仅展示附加费用合计，这里暂按选中附加费用求和
				return this.extraFees
					.filter(i => i.selected)
					.reduce((sum, i) => sum + Number(i.price || 0), 0)
			}
		},
		async onLoad(query) {
			if (query && query.orderId) {
				this.orderId = query.orderId
			}

			if (query && query.masterOrderDataFee){
				this.masterOrderDataFee = query.masterOrderDataFee;
			}

			if (query && query.additionalFeeList) {
				this.additionalFeeList = JSON.parse(decodeURIComponent(query.additionalFeeList));
				console.log("additionalFeeList",this.additionalFeeList);
			}




			// 先加载配置数据
			this.loadConfig()
			await this.getProductTypeData();
			this.getCurtainsTypeData();
			this.getremoteFees();
			this.getProductadditionalFee();
			this.getspecialWall();

			// 如果携带安装数据 id，则请求详情并回填，并控制可编辑态
			if (query && query.id) {
				this.id = query.id;
				this.canEdit = false
				this.loadDetail(query.id)
			} else {
				this.canEdit = true
			}
		},
		methods: {
			goBack() {
				uni.navigateBack()
			},
			// 选择/拍摄照片
			pickImage() {
				if (this.form.photos && this.form.photos.length >= 3) {
					uni.showToast({
						title: '最多上传3张照片',
						icon: 'none'
					})
					return
				}

				const remainCount = 3 - (this.form.photos ? this.form.photos.length : 0)

				uni.chooseImage({
					count: remainCount,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: async (res) => {
						console.log('选择照片成功:', res);

						if (!this.form.photos) {
							this.form.photos = []
						}

						// 显示上传提示
						uni.showLoading({
							title: '正在上传照片...'
						})

						try {
							const uploadPromises = res.tempFilePaths.map(async (filePath) => {
								// 生成唯一文件名
								const timestamp = Date.now()
								const random = Math.random().toString(36).substring(2, 8)
								const fileName = `installation_photos/${timestamp}_${random}.jpg`
								return await uploadFile(fileName, filePath)
							})

							// 等待所有照片上传完成
							const uploadedUrls = await Promise.all(uploadPromises).then(results => {
								return results.map(result => result.url);
							})
							console.log('上传结果:', uploadedUrls)
							// 添加到照片列表
							console.log('上传前的照片列表:', this.form.photos)
							console.log('新上传的URLs:', uploadedUrls)

							// 确保 form.photos 是响应式的
							this.$set(this.form, 'photos', [...this.form.photos, ...uploadedUrls])

							console.log('上传后的照片列表:', this.form.photos)


							this.updateOrderData()
							// 强制更新视图
							this.$forceUpdate()

							uni.hideLoading()
							uni.showToast({
								title: '上传成功',
								icon: 'success'
							})

						} catch (error) {
							console.error('上传失败:', error)
							uni.hideLoading()
							uni.showToast({
								title: '上传失败，请重试',
								icon: 'none'
							})
						}
					}
				})
			},

			updateOrderData() {
				if (!this.form.photos || !this.form.photos.length) {
					uni.showToast({
						title: '请至少上传一张照片',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					title: '提交中...'
				})

				var picStr = '';
				for (var i = 0; i < this.form.photos.length; i++) {
					picStr +=  (i+1)+'image.png'+'@##@'+this.form.photos[i] + '#@@#'
				}
				picStr = picStr.substring(0,picStr.length-4);
				

				const data = {
					id: this.id,
					dataPicture: picStr
				}

				editOrderData(data)
					.then(res => {
						if (res.code === 200) {
							uni.showToast({
								title: '提交成功',
								icon: 'success'
							})
						} else {
							uni.showToast({
								title: res.msg || '提交失败',
								icon: 'none'
							})
						}
					})
					.catch(err => {
						console.error('提交安装数据失败:', err)
						uni.showToast({
							title: '提交失败，请重试',
							icon: 'none'
						})
					})
					.finally(() => {
						uni.hideLoading()
					})
			},
			// 删除照片
			deletePhoto(index) {
				console.log('删除照片，索引:', index)
				console.log('删除前的照片列表:', this.form.photos)

				// 使用响应式方法删除照片
				this.$set(this.form, 'photos', this.form.photos.filter((_, i) => i !== index))

				console.log('删除后的照片列表:', this.form.photos)

				this.updateOrderData()

				// 强制更新视图
				this.$forceUpdate()

				uni.showToast({
					title: '删除成功',
					icon: 'success',
					duration: 1000
				})
			},
			// 加载安装数据详情并回填
			async loadDetail(id) {
				try {
					uni.showLoading({
						title: '加载中...'
					})
					const res = await getOrderDataDetail(id)
					if (res && res.code === 200 && res.data) {
						const d = res.data.orderData
						this.form = d || {}

						this.form.productTypeName = this.getProductTypeName(d.productType);
						
						this.form.curtainsTypeName = this.getCurtainsTypeName(d.curtainsType);
						console.log("dataPicture",d.dataPicture)
						var picArr = [];
						if(d.dataPicture){
							var splitPic = d.dataPicture.split('#@@#');
							console.log(splitPic)
							splitPic.forEach(item=>{
								var tempArr = item.split('@##@');
								picArr.push(tempArr[1]	);
							})
							
						}
						this.form.photos = picArr;

						if (!this.form.photos) this.form.photos = []

						const feeList = res.data.feeConfigList
						const arr = [];
						for (let i = 0; i < feeList.length; i++) {
							const item = {};
							item.discountStoreFee = Number(feeList[i].discountStoreFee);
							item.storeFee = Number(feeList[i].storeFee);
							item.detailedType = feeList[i].detailedType;
							item.projectName = feeList[i].projectName;
							item.amount = item.discountStoreFee ? item.discountStoreFee : item.storeFee;
							item.name = this.getFeeName(item.detailedType, item.projectName)
							arr.push(item)
						}


						// 附加费用

						this.extraFees = arr.map(i => ({
							name: i.name || i.label || '',
							price: Number(i.price || i.amount || 0),
							selected: !!i.selected
						}))

					} else {
						uni.showToast({
							title: res.msg || '加载失败',
							icon: 'none'
						})
					}
				} catch (e) {
					console.error(e)
				} finally {
					uni.hideLoading()
				}
			},

			// 配置数据：产品/窗幔类型/附加费用从后端加载（若接口返回）
			loadConfig() {
				/**
      try {
        const res = await confgiList({})
        if (res && res.code === 200 && res.data) {
          // 根据实际返回结构进行适配，这里尝试常见字段名
          if (Array.isArray(res.data.productOptions) && res.data.productOptions.length) {
            this.productOptions = res.data.productOptions
          }
          if (Array.isArray(res.data.valanceOptions) && res.data.valanceOptions.length) {
            this.valanceOptions = res.data.valanceOptions
          }
          if (Array.isArray(res.data.extraFees) && res.data.extraFees.length) {
            this.extraFees = res.data.extraFees.map(i => ({
              name: i.name || i.label || '',
              price: Number(i.price || i.amount || 0),
              selected: false
            }))
          }
        }
      } catch (e) {
        // 静默处理，使用默认选项
      }
         */
			},
			getFeeName(detailedType, projectName) {
				if (detailedType == '41') {
					return "超高费";
				} else {
					if (detailedType == 'remoteFees') {
						for (let i = 0; i < this.remoteFees.length; i++) {
							if (this.remoteFees[i].paramValue == projectName) {
								return "远程费-" + this.remoteFees[i].paramName;
							}
						}

					} else if (detailedType == 'specialWall') {
						for (let i = 0; i < this.specialWall.length; i++) {
							if (this.specialWall[i].paramValue == projectName) {
								return "特殊墙体-" + this.specialWall[i].paramName;
							}
						}
					} else {
						return '';
					}

				}

			},

			getProductadditionalFee() {
				confgiList({
						parentSign: 'additionalFee'
					})
					.then(res => {
						if (res && res.code === 200) {
							this.additionalFee = Array.isArray(res.data) ? res.data : [];
						} else {
							this.additionalFee = [];
						}
					})
					.catch(() => {
						this.additionalFee = [];
					});
			},
			getremoteFees() {
				confgiList({
						parentSign: 'remoteFees'
					})
					.then(res => {
						if (res && res.code === 200) {
							this.remoteFees = Array.isArray(res.data) ? res.data : [];
						} else {
							this.remoteFees = [];
						}
					})
					.catch(() => {
						this.remoteFees = [];
					});
			},
			getspecialWall() {
				confgiList({
						parentSign: 'specialWall'
					})
					.then(res => {
						if (res && res.code === 200) {
							this.specialWall = Array.isArray(res.data) ? res.data : [];
						} else {
							this.specialWall = [];
						}
					})
					.catch(() => {
						this.specialWall = [];
					});
			},


			getProductTypeData() {
				return confgiList({
						parentSign: 'productType'
					})
					.then(res => {
						if (res && res.code === 200) {
							this.productType = Array.isArray(res.data) ? res.data : [];
						} else {
							this.productType = [];
						}
					})
					.catch(() => {
						this.productType = [];
					});
			},

			getProductTypeName(val) {
				for (let i = 0; i < this.productType.length; i++) {
					if (this.productType[i].paramValue == val) {
						return this.productType[i].paramName;
					}
				}
				return '';
			},



			getCurtainsTypeData() {
				confgiList({
						parentSign: 'curtainsType'
					})
					.then(res => {
						if (res && res.code === 200) {
							this.curtainsType = Array.isArray(res.data) ? res.data : [];
						} else {
							this.curtainsType = [];
						}
					})
					.catch(() => {
						this.curtainsType = [];
					});
			},

			getCurtainsTypeName(val) {
				for (let i = 0; i < this.curtainsType.length; i++) {
					if (this.curtainsType[i].paramValue == val) {
						return this.curtainsType[i].paramName;
					}
				}
				return '';
			},


			// 房间名称
			openRoomSelector() {
				if (!this.canEdit) return
				this.roomSelectorVisible = true
			},
			onRoomConfirm(val) {
				this.form.roomName = val
				this.roomSelectorVisible = false
			},
			// 产品
			chooseProduct() {
				if (!this.canEdit) return
				uni.showActionSheet({
					itemList: this.productOptions,
					success: ({
						tapIndex
					}) => {
						this.form.productName = this.productOptions[tapIndex]
					}
				})
			},

			// 数量
			chooseQuantity() {
				if (!this.canEdit) return
				const nums = Array.from({
					length: 10
				}, (_, i) => String(i + 1))
				uni.showActionSheet({
					itemList: nums,
					success: ({
						tapIndex
					}) => {
						this.form.installNum = Number(nums[tapIndex])
					}
				})
			},

			// 有无窗幔与类型
			chooseValance() {
				if (!this.canEdit) return
				const firstStep = ['有', '无']
				uni.showActionSheet({
					itemList: firstStep,
					success: ({
						tapIndex
					}) => {
						const has = firstStep[tapIndex] === '有'
						this.form.isCurtains = has ? '2' : '1'
						if (!has) {
							this.form.curtainsType = ''
							this.form.curtainsTypeName = ''
							return
						}
						// 选择类型
						if (this.curtainsType.length > 0) {
							uni.showActionSheet({
								itemList: this.curtainsType.map(item => item.paramName),
								success: ({
									tapIndex: idx
								}) => {
									this.form.curtainsType = this.curtainsType[idx].paramValue
									this.form.curtainsTypeName = this.curtainsType[idx].paramName
								}
							})
						}
					}
				})
			},

			// 输入数字
			inputNumber(field, title) {
				if (!this.canEdit) return
				uni.showModal({
					title: title || '请输入数字',
					editable: true,
					placeholderText: '仅支持数字',
					success: ({
						confirm,
						content
					}) => {
						if (!confirm) return
						const v = Number(content)
						if (Number.isNaN(v) || v <= 0) {
							uni.showToast({
								title: '请输入有效数字',
								icon: 'none'
							})
							return
						}
						// 映射字段名
						if (field === 'width') {
							this.form.windowWidth = v
						} else if (field === 'height') {
							this.form.windowHeight = v
						} else {
							this.form[field] = v
						}
					}
				})
			},
			// 切换附加费用
			toggleFee(index) {
				if (!this.canEdit) return
				this.extraFees[index].selected = !this.extraFees[index].selected
			},
			// 预留提交
			submit() {
				// TODO: 与后端对接提交安装数据
				// 可参考 api/app/master/order.js 新增接口后在此调用
				console.log('提交安装数据', {
					...this.form,
					orderId: this.orderId,
					total: this.totalPrice
				})
				uni.showToast({
					title: '已保存(示例)',
					icon: 'none'
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.add-installation-container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 120rpx;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		height: 90rpx;
		background-color: #0088ff;
		color: #fff;
		padding: 0 30rpx;
		position: relative;
	}

	.back-btn {
		position: absolute;
		left: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.back-icon-img {
		width: 40rpx;
		height: 40rpx;
	}

	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
	}

	.scroll-body {
		height: calc(100vh - 90rpx);
	}

	.block {
		background-color: #fff;
		padding: 20rpx 30rpx;
	}

	.block-title {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 10rpx;
	}

	.photo-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.photo-item {
		position: relative;
		width: 200rpx;
		height: 200rpx;
		border-radius: 12rpx;
		overflow: hidden;
	}

	.photo-uploader {
		width: 200rpx;
		height: 200rpx;
		border: 2rpx dashed #ddd;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
	}

	.photo-placeholder {
		width: 100%;
		height: 100%;
		background-color: #f7f7f7;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.camera-icon {
		width: 60rpx;
		height: 60rpx;
		opacity: 0.6;
		margin-bottom: 10rpx;
	}

	.upload-text {
		font-size: 24rpx;
		color: #999;
	}

	.photo-preview {
		width: 100%;
		height: 100%;
	}

	.photo-delete {
		position: absolute;
		top: -10rpx;
		right: -10rpx;
		width: 40rpx;
		height: 40rpx;
		background-color: #ff3b30;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.delete-icon {
		color: #fff;
		font-size: 50rpx;
		font-weight: bold;
		line-height: 1;
	}

	.photo-tip {
		margin-top: 20rpx;
		text-align: center;
	}

	.photo-tip text {
		font-size: 24rpx;
		color: #999;
	}

	.divider {
		height: 16rpx;
		background-color: #f5f5f5;
	}

	.list {
		background-color: #fff;
	}

	.row {
		display: flex;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.label {
		flex: 0 0 220rpx;
		font-size: 30rpx;
		color: #333;
		font-weight: 600;
	}

	.value {
		flex: 1;
		text-align: right;
		font-size: 28rpx;
		color: #333;
	}

	.fees {
		background-color: #fff;
	}

	.fee-item {
		display: flex;
		align-items: center;
		padding: 24rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
		justify-content: space-between;
	}

	.fee-name {
		font-size: 28rpx;
		color: #000;
	}

	.fee-name.dim {
		color: #000;
	}

	.fee-price {
		font-size: 30rpx;
		color: #f00;
		font-weight: 600;
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 30rpx;
		border-top: 1rpx solid #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}

	.total-label {
		font-size: 30rpx;
		color: #333;
		margin-right: 8rpx;
		font-weight: 600;
	}

	.total-price {
		font-size: 48rpx;
		color: #ff3b30;
		font-weight: 700;
	}

	.submit-btn {
		height: 72rpx;
		line-height: 72rpx;
		padding: 0 28rpx;
		background-color: #0088ff;
		color: #fff;
		border-radius: 36rpx;
		font-size: 28rpx;
	}

	.disabled {
		opacity: 0.6;
		pointer-events: none;
	}
</style>